"""Contains the main menu and game loop for Ruin"""

import argparse
from pyre.core import term, types
from pyre.ui import widgit, menu, element
import ruin.resource
import ruin.world
import ruin.player

def game_loop(terminal):
    """
    game_loop(Terminal): None
    Runs the main game loop for Ruin
    """

    world = ruin.world.Overworld(60, 60)
    player = ruin.player.Player(terminal)
    world.add_actor(player)

    terminal.add_widgit(player.camera, (0, 0), (30, 15))
    terminal.add_widgit(widgit.MessageBox(player), (0, 16), (50, 8))
    terminal.add_widgit(widgit.TextDisplay(player.info), (31, 0), (19, 24))

    while not player.expired:
        player.aggregate_messages(player.world)
        terminal.clear_buffer()
        terminal.update_widgits()
        terminal.refresh_screen()
        player.world.tick()

    terminal.clear_widgits()


def get_term(cols, rows, title, args):
    """
    get_term(int, int, title, Namespace)
    Returns the appropriate terminal given the arguments
    """

    if args.term or not term.PYGAME_ENABLED:
        return term.AnsiTerminal(cols, rows, title)
    else:
        terminal = term.PygameTerminal(cols, rows, title, args.font, args.size)
        if args.graphics:
            sprites = ruin.resource.get_sprites(terminal.tile_size)
            terminal.sprite_cache = sprites
        return terminal


def main():
    """
    main(): None
    Starts up the Ruin game
    """

    ruin_desc = 'Ruin is yet another vaporware roguelike'
    parser = argparse.ArgumentParser(description=ruin_desc)
    parser.add_argument('-t', '--term', action='store_true', default=False,
                        help='force the use of the ansi terminal')
    parser.add_argument('-f', '--font', default=ruin.resource.fontname,
                        help='set a custom font')
    parser.add_argument('-s', '--size', type=int, default=15,
                        help='set a custom font size')
    parser.add_argument('-g', '--graphics', action='store_true', default=False,
                        help='use graphical tiles')
    args = parser.parse_args()

    with get_term(50, 24, 'RuinRL', args) as terminal:
        main_menu = menu.Menu(ruin.resource.menu_data_location)

        while True:
            choice = main_menu.run(terminal)

            if choice == 'New game':
                game_loop(terminal)
            elif choice == 'Load game':
                terminal.clear_buffer()
                element.popup_text(terminal, 'Load game not implemented')
            elif choice == 'Exit':
                break
